﻿using System;
using System.Collections.Generic;
using Newtonsoft.Json.Linq;
using TrinityAPI.Base.Tools;
using TrinityAPI.Base.Models;

namespace TrinityAPI.Base
{
    public class GenerateAuthKey : IAction
    {
        public JToken Invoke(JObject dataset, params JToken[] args)
        {
            var query = dataset.GetJsonObject("query");
            var request = dataset.GetJsonObject("request");
            var constant = dataset.GetJsonObject("constant");
            var connection = constant.GetJsonObject("connection");
            var oms = connection.GetNecessaryJsonObject("oms", "constant.connection");

            var authentication = constant.GetJsonObject("authentication");
            var systemcode = authentication.GetJsonObjectStringValue("systemcode");
            if (string.IsNullOrWhiteSpace(systemcode))
                systemcode = constant.GetNecessaryJsonObjectStringValue("systemcode", "constant");

            string apiKey = request.GetJsonObjectStringValue("apiKey");
            string requestTime = request.GetJsonObjectStringValue("requestTime");
            if (string.IsNullOrWhiteSpace(apiKey))
                apiKey = query.GetJsonObjectStringValue("apiKey");
            if (string.IsNullOrWhiteSpace(requestTime))
                requestTime = query.GetJsonObjectStringValue("requestTime");

            if (string.IsNullOrWhiteSpace(apiKey) || string.IsNullOrWhiteSpace(requestTime))
                throw ExceptionHelper.GenException(ErrorCode.E000000021, "[apiKey] and [requestTime]");

            string secretKey = null;
            string sql = "SELECT SerectKey FROM API_APIKey WHERE APICode=@APICode AND APIKey=@APIKey AND Disabled=0";
            var dbBase = Utils.GetDBAdapter("oms", oms, null, false);
            var obj = dbBase.ExecuteScalar(sql, new List<DBParameter>() { new DBParameter("@APICode", systemcode), new DBParameter("@APIKey", apiKey) }, System.Data.CommandType.Text);
            if (obj != null)
                secretKey = obj.ToString();

            if (string.IsNullOrWhiteSpace(secretKey))
                throw new Exception("The [apiKey] is invalid or config error");

            return Utils.MD5(apiKey + requestTime + secretKey, System.Text.Encoding.UTF8, true);
        }
    }
}
